<template>
  <div class="sale-returns-page">
    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" inline class="filter-form">
        <el-form-item label="退货单号">
          <el-input
            v-model="searchForm.saleReturnsNo"
            placeholder="请输入"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select
            v-model="searchForm.saleReturnsStatus"
            placeholder="请选择"
            clearable
            style="width: 160px"
          >
            <el-option
              v-for="item in SALE_RETURN_STATUS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-select
            v-model="searchForm.customerName"
            placeholder="请选择"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售日期">
          <el-date-picker
            v-model="searchForm.salesDate"
            type="date"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            placeholder="请选择"
            style="width: 180px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleAdvancedSearch">高级搜索</el-button>
        </el-form-item>
      </el-form>
      <div class="action-bar">
        <el-button type="success" @click="handleAdd">新增</el-button>
        <el-button @click="handleBatchDelete">批量删除</el-button>
        <el-button @click="fetchSaleReturns">刷新</el-button>
      </div>
    </el-card>

    <el-card class="table-card" shadow="never">
      <el-table
        ref="tableRef"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="销售退货单号" prop="saleReturnsNo" min-width="150">
          <template #default="{ row }">
            <el-link type="primary" @click="handleDetail(row)">
              {{ row.saleReturnsNo || '-' }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="单据状态" prop="saleReturnsStatus" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.saleReturnsStatus)" size="small">
              {{ row.saleReturnsStatusName || getStatusText(row.saleReturnsStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="退货日期" prop="saleReturnsDate" width="140">
          <template #default="{ row }">
            {{ formatDate(row.saleReturnsDate) }}
          </template>
        </el-table-column>
        <el-table-column label="销售单号" prop="salesOrderNo" min-width="140">
          <template #default="{ row }">
            {{ row.salesOrderNo || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="客户名称" prop="customerName" min-width="160" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.customerName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="联系人" prop="contactName" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.contactName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="联系方式" prop="contactPhone" width="140" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.contactPhone || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="销售部门" prop="salesDepartment" width="140" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.salesDepartment || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="销售负责人" prop="salesOwner" width="140" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.salesOwner || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="退货数量" prop="saleReturnsQuantity" width="110" align="right">
          <template #default="{ row }">
            {{ Number(row.saleReturnsQuantity ?? 0) }}
          </template>
        </el-table-column>
        <el-table-column label="退货金额" prop="saleReturnsAmount" width="120" align="right">
          <template #default="{ row }">
            ¥{{ Number(row.saleReturnsAmount ?? 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="退货货品" prop="productNames" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="goods-text">
              {{ row.productNames || row.saleReturnsGoodsText || row.productName || '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="制单人" width="110" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.creator || row.createor || row.createUser || row.saleReturnsUser || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="所在部门" prop="organizationName" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.organizationName || row.salesDepartment || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="制单时间" prop="saleReturnsTime" width="170">
          <template #default="{ row }">
            {{ formatDateTime(row.saleReturnsTime || row.createTime) || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="审核人" width="110" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.auditor || currentUserName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="审核时间" prop="auditTime" width="170">
          <template #default="{ row }">
            {{ formatDateTime(row.auditTime) || formatDateTime(currentTime) || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-bar">
        <el-pagination
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="fetchSaleReturns"
          @current-change="fetchSaleReturns"
        />
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import router from '@/router'
import myaxios from '@/http/MyAxios'

const SALE_RETURN_STATUS = [
  { value: '', label: '全部', tagType: 'info' },
  { value: 0, label: '草稿', tagType: 'info' },
  { value: 1, label: '待审核', tagType: 'warning' },
  { value: 2, label: '部分出库', tagType: 'warning' },
  { value: 3, label: '已出库', tagType: 'success' },
  { value: 4, label: '驳回', tagType: 'danger' },
  { value: 5, label: '关闭', tagType: 'danger' },
  { value: 6, label: '未入库', tagType: 'warning' },
  { value: 7, label: '部分入库', tagType: 'warning' },
  { value: 8, label: '已完成', tagType: 'success' },
]

const searchForm = reactive({
  saleReturnsNo: '',
  saleReturnsStatus: '',
  customerName: '',
  salesDate: '',
  saleReturnsDateRange: [] as string[],
})

// 客户选项列表
const customerOptions = ref<Array<{ label: string; value: string }>>([])

const tableData = ref<any[]>([])
const loading = ref(false)
const pagination = reactive({
  pageindex: 1,
  pagesize: 10,
  total: 0,
})
const multipleSelection = ref<any[]>([])

// 当前登录用户信息
const currentUserName = ref<string>('')
const currentTime = ref<string>(moment().format('YYYY-MM-DD HH:mm:ss'))

// 获取当前登录用户信息
const loadCurrentUser = async () => {
  try {
    const res = await myaxios.get('/api/User/GetMyProfile')
    const droot: any = res?.data ?? {}
    const d: any = (droot?.data && Object.keys(droot).length <= 3) ? (droot.data || {}) : droot
    if (d) {
      // 优先使用真实姓名，其次用户名，最后账号
      currentUserName.value = d.userName || d.realName || d.nickname || localStorage.getItem('username') || ''
      // 如果获取到了，更新localStorage
      if (currentUserName.value) {
        localStorage.setItem('username', currentUserName.value)
      }
    } else {
      // 如果接口失败，使用localStorage中的值
      currentUserName.value = localStorage.getItem('username') || ''
    }
  } catch (error) {
    // 如果接口失败，使用localStorage中的值
    console.warn('获取当前用户信息失败，使用本地存储的值:', error)
    currentUserName.value = localStorage.getItem('username') || ''
  }
  // 更新当前时间
  currentTime.value = moment().format('YYYY-MM-DD HH:mm:ss')
}

const normalizeList = (payload: any) => {
  if (!payload) return []
  if (Array.isArray(payload)) return payload
  if (Array.isArray(payload?.data)) return payload.data
  if (Array.isArray(payload?.records)) return payload.records
  if (Array.isArray(payload?.list)) return payload.list
  if (Array.isArray(payload?.items)) return payload.items
  return []
}

const formatDate = (value?: string) => {
  if (!value) return '-'
  return moment(value).format('YYYY-MM-DD')
}

const formatDateTime = (value?: string) => {
  if (!value) return '-'
  return moment(value).format('YYYY-MM-DD HH:mm:ss')
}

const getStatusText = (value: number | string) => {
  const matched = SALE_RETURN_STATUS.find((item) => String(item.value) === String(value))
  return matched?.label || '未知'
}

const getStatusTag = (value: number | string) => {
  const matched = SALE_RETURN_STATUS.find((item) => String(item.value) === String(value))
  return matched?.tagType || 'info'
}

// 判断是否可以编辑/删除（草稿、待审核状态）
const canEdit = (status: number | string) => {
  const statusValue = Number(status)
  return statusValue === 0 || statusValue === 1 // 草稿、待审核
}

// 判断是否可以撤销（驳回、未入库状态）
const canRevoke = (status: number | string) => {
  const statusValue = Number(status)
  return statusValue === 4 || statusValue === 6 // 驳回、未入库
}

// 数据映射函数，从后端数据中提取字段（根据实际后端字段名）
const mapSaleReturnRecord = (item: any) => {
  // 提取货品信息 - 优先从顶层productName获取，如果没有则从明细中提取
  let productNames: string[] = []
  
  // 如果顶层有productName，直接使用
  if (item.productName) {
    productNames = [item.productName]
  } else {
    // 否则从明细中提取
    const details = item.saleReturnsDetails || item.details || item.saleReturnDetails || []
    if (Array.isArray(details) && details.length > 0) {
      details.forEach((detail: any) => {
        const productName = detail.productName || detail.productname || detail.goodsName || ''
        if (productName && !productNames.includes(productName)) {
          productNames.push(productName)
        }
      })
    }
  }

  // 构建货品名称字符串
  const productNamesText = productNames.length > 0 
    ? productNames.join('、') 
    : (item.productNames || item.saleReturnsGoodsText || item.productName || '')

  return {
    // 基本信息 - 使用后端实际字段名
    saleReturnsId: item.saleReturnsId,
    saleReturnsNo: item.saleReturnsNo || '',
    saleReturnsStatus: item.saleReturnsStatus ?? 0,
    saleReturnsStatusName: item.saleReturnsStatusName || '', // 后端返回的状态名称
    saleReturnsDate: item.saleReturnsDate || '',
    salesOrderId: item.salesOrderId,
    salesOrderNo: item.salesOrderNo || item.saleOrderNo || item.orderNo || '',
    customerId: item.customerId,
    customerName: item.customerName || item.customer || '',
    
    // 联系人信息 - 使用后端字段名 saleReturnsContact 和 saleReturnsContactPhone
    contactName: item.saleReturnsContact || item.contactName || item.linkMan || item.contact || '',
    contactPhone: item.saleReturnsContactPhone || item.contactPhone || item.linkPhone || item.contactMethod || '',
    
    // 部门信息 - 使用后端字段名 saleReturnsDepartment 和 organizationName
    salesDepartment: item.saleReturnsDepartment || item.organizationName || item.salesDepartment || item.department || '',
    organizationName: item.organizationName || item.saleReturnsDepartment || item.departmentName || item.department || '',
    
    // 负责人信息 - 使用后端字段名 saleReturnsUser 和 userName
    salesOwner: item.saleReturnsUser || item.userName || item.salesOwner || item.salesManager || '',
    userName: item.userName || item.saleReturnsUser || item.salesOwner || item.salesManager || '',
    
    // 数量和金额
    saleReturnsQuantity: item.saleReturnsQuantity ?? 0,
    saleReturnsAmount: item.saleReturnsAmount ?? 0,
    
    // 货品信息
    productNames: productNamesText,
    saleReturnsGoodsText: productNamesText,
    productName: item.productName || '',
    
    // 制单人、制单时间 - 使用后端字段名
    // 注意：后端可能没有直接返回制单人字段，可能需要从其他字段推断
    creator: item.creator || item.createor || item.createUser || item.documentMaker || item.makerName || item.saleReturnsUser || '',
    createor: item.createor || item.creator || item.createUser || item.documentMaker || item.makerName || item.saleReturnsUser || '',
    createUser: item.createUser || item.creator || item.createor || item.documentMaker || item.makerName || item.saleReturnsUser || '',
    
    // 制单时间 - 使用后端字段名 saleReturnsTime
    createTime: item.saleReturnsTime || item.createTime || item.documentTime || item.makerTime || '',
    saleReturnsTime: item.saleReturnsTime || item.createTime || item.documentTime || item.makerTime || '',
    
    // 审核人、审核时间 - 使用后端字段名
    auditor: item.auditor || '',
    auditTime: item.auditTime || '',
    
    // 其他字段（兼容）
    saleReturnsReason: item.saleReturnsReason || '',
    saleReturnsRemark: item.saleReturnsRemark || '',
    organizationId: item.organizationId,
    userId: item.userId,
  }
}

// 加载客户列表
const loadCustomerOptions = async () => {
  try {
    const res = await myaxios.get('/api/Customer/GetCustomers', {
      params: { pageindex: 1, pagesize: 1000 },
    })
    if (res?.data?.code === 200 || res?.data?.success) {
      const section = res.data?.data ?? res.data
      const list = normalizeList(section)
      customerOptions.value = list.map((item: any) => ({
        label: item.customerName || item.customer || item.name || '',
        value: item.customerName || item.customer || item.name || '',
      }))
      // 去重
      const uniqueMap = new Map()
      customerOptions.value = customerOptions.value.filter((item) => {
        if (item.value && !uniqueMap.has(item.value)) {
          uniqueMap.set(item.value, true)
          return true
        }
        return false
      })
    }
  } catch (error) {
    console.warn('加载客户列表失败:', error)
  }
}

const fetchSaleReturns = async () => {
  loading.value = true
  try {
    const params: Record<string, any> = {
      saleReturnsNo: searchForm.saleReturnsNo,
      saleReturnsStatus: searchForm.saleReturnsStatus,
      customerName: searchForm.customerName,
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize,
    }
    if (searchForm.salesDate) {
      params.salesDate = searchForm.salesDate
    }
    if (searchForm.saleReturnsDateRange?.length === 2) {
      params.startDate = searchForm.saleReturnsDateRange[0]
      params.endDate = searchForm.saleReturnsDateRange[1]
    }
    const res = await myaxios.get('/api/SaleReturns/GetSaleReturns', { params })
    if (res?.data?.code === 200 || res?.data?.success) {
      const section = res.data?.data ?? res.data
      const list = normalizeList(section)
      // 映射数据，提取货品信息等字段
      tableData.value = list.map(mapSaleReturnRecord)
      pagination.total =
        section?.listCount ?? section?.total ?? section?.recordsTotal ?? list.length
    } else {
      tableData.value = []
      pagination.total = 0
      ElMessage.error(res?.data?.message || '获取销售退货列表失败')
    }
  } catch (error) {
    console.error('获取销售退货列表失败:', error)
    tableData.value = []
    pagination.total = 0
    ElMessage.error('获取销售退货列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageindex = 1
  fetchSaleReturns()
}

const handleReset = () => {
  searchForm.saleReturnsNo = ''
  searchForm.saleReturnsStatus = ''
  searchForm.customerName = ''
  searchForm.salesDate = ''
  searchForm.saleReturnsDateRange = []
  handleSearch()
}

const handleSelectionChange = (rows: any[]) => {
  multipleSelection.value = rows
}

const handleAdd = () => {
  router.push('/createsalereturn')
}

const handleDetail = (row: any) => {
  if (!row?.saleReturnsId) {
    ElMessage.warning('缺少销售退货ID')
    return
  }
  router.push({
    path: '/detailsalereturn',
    query: { saleReturnsId: row.saleReturnsId },
  })
}

const handleEdit = (row: any) => {
  if (!row?.saleReturnsId) {
    ElMessage.warning('缺少销售退货ID')
    return
  }
  router.push({
    path: '/updatesalereturn',
    query: { saleReturnsId: row.saleReturnsId },
  })
}

const handleDelete = (row: any) => {
  if (!row?.saleReturnsId) {
    ElMessage.warning('缺少销售退货ID')
    return
  }
  ElMessageBox.confirm('确认删除该销售退货单吗？', '提示', {
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await myaxios.delete('/api/SaleReturns/DeleteSaleReturns', {
          params: { saleReturnsId: row.saleReturnsId },
        })
        if (res?.data?.code === 200) {
          ElMessage.success(res?.data?.message || '删除成功')
          fetchSaleReturns()
        } else {
          ElMessage.error(res?.data?.message || '删除失败')
        }
      } catch (error) {
        console.error('删除销售退货失败:', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {})
}

const handleRevoke = (row: any) => {
  if (!row?.saleReturnsId) {
    ElMessage.warning('缺少销售退货ID')
    return
  }
  ElMessageBox.confirm('确认撤销该销售退货单吗？', '提示', {
    type: 'warning',
  })
    .then(async () => {
      try {
        // TODO: 调用撤销接口
        ElMessage.warning('撤销功能正在开发中')
        // const res = await myaxios.post('/api/SaleReturns/RevokeSaleReturns', {
        //   saleReturnsId: row.saleReturnsId,
        // })
        // if (res?.data?.code === 200) {
        //   ElMessage.success(res?.data?.message || '撤销成功')
        //   fetchSaleReturns()
        // } else {
        //   ElMessage.error(res?.data?.message || '撤销失败')
        // }
      } catch (error) {
        console.error('撤销销售退货失败:', error)
        ElMessage.error('撤销失败，请稍后重试')
      }
    })
    .catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请勾选需要操作的单据!')
    return
  }
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条销售退货单吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const ids = multipleSelection.value.map((item) => item.saleReturnsId).filter(Boolean)
        if (ids.length === 0) {
          ElMessage.warning('没有有效的销售退货ID')
          return
        }
        
        // 尝试使用 DELETE 请求，参数在 URL 中（参考进货退货的实现）
        const res = await myaxios.delete('/api/SaleReturns/BatchDeleteSaleReturns', {
          params: { ids: ids.join(',') },
        })
        
        if (res?.data?.code === 200) {
          ElMessage.success(res?.data?.message || '批量删除成功')
          // 清空选中状态
          multipleSelection.value = []
          fetchSaleReturns()
        } else {
          ElMessage.error(res?.data?.message || '批量删除失败')
        }
      } catch (error: any) {
        console.error('批量删除销售退货失败:', error)
        // 如果 DELETE 请求失败，尝试使用 POST 请求（参考销售订单的实现）
        try {
          const ids = multipleSelection.value.map((item) => item.saleReturnsId).filter(Boolean)
          const res = await myaxios.post('/api/SaleReturns/DeleteSaleReturns', {
            ids: ids,
          })
          
          if (res?.data?.code === 200) {
            ElMessage.success(res?.data?.message || '批量删除成功')
            // 清空选中状态
            multipleSelection.value = []
            fetchSaleReturns()
          } else {
            ElMessage.error(res?.data?.message || '批量删除失败')
          }
        } catch (retryError: any) {
          console.error('重试批量删除失败:', retryError)
          ElMessage.error(retryError?.response?.data?.message || '批量删除失败，请稍后重试')
        }
      }
    })
    .catch(() => {})
}



// 高级搜索
const handleAdvancedSearch = () => {
  ElMessage.info('高级搜索功能正在开发中')
}

onMounted(() => {
  loadCurrentUser() // 加载当前登录用户信息
  loadCustomerOptions() // 加载客户列表
  fetchSaleReturns()
})
</script>

<style scoped>
.sale-returns-page {
  padding: 16px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 12px;
}

.action-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
}

.table-card {
  margin-top: 12px;
}

.pagination-bar {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
}

.goods-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

